/**
 *
 *
 * @author TOTORO
 * @date 2021/6/23 10:05
 */

var webSocket;
window.onload = function () {
    // 登录才链接
    $.ajaxSettings.async = false;
    $.post("/user_logic/userStatus.htm", res=>{
       if(res == "no"){
           return false;
       }
        var $pb = $(".chat-box",window.parent.document);
        // 点击打开聊天框，让表情div跟随聊天页面
        var top = $pb.css("top");
        var left = $pb.css("left");
        $("#emoji_container_1").css({"top":(parseInt(top)+261)+"px","left":(parseInt(left)+253)+"px"});
        var mainContainer = $('.cc-content');
        mainContainer.scrollTop(9999999);
        var host = window.location.host;
        webSocket =
            new WebSocket("ws://" + host+ "/ws?id=1");
        var hum = null;
        var s_json = null;
        webSocket.onerror = function(event) {
            onError(event);
        };
        webSocket.onopen = function(event) {
            onOpen(event);
        };
        webSocket.onmessage = function(event) {
            onMessage(event);
        };
        webSocket.onclose = function (event) {
            console.log("断开连接")
        }
        function onMessage(event) {
            // 收到某个用户发来的消息
            var json = eval("("+ event.data +")")
            var text = json.sendMessage;
            var suMainChatId = json.suMainChatId;
            // 判断用户是否打开了聊天面板并选中了本次聊天栏
            var $pb = $(".chat-box",window.parent.document);
            var isShow = $pb.css("display")=='block'?true:false;
            // 打开了聊天面板
            if(isShow){
                // 判断是否选中了本次聊天栏
                var $selectedMainChat = $(".cl-seller-item.selected");
                // 修改这次聊天栏的默认消息
                // 获取发送方发送消息过来的那个左侧选择栏
                var $sendMainChat = $(".cl-seller-item[data-sm-id='"+suMainChatId+"']");
                $sendMainChat.find(".cl-seller-synopsis").html(Totoro.cutOutImgPrefix(text, "[图片]"));
                if(parseInt($selectedMainChat.attr("data-sm-id")) == parseInt(suMainChatId)) {
                    var thatHead = $sendMainChat.find(".cl-seller-head img").attr("src");
                    // 直接渲染在聊天栏上
                    // 判断聊天栏最后一条信息的时间
                    var $lastChat = $(".cc-content").children(".clear-float:last-child");
                    // 如果没有消息记录，则默认生成带有时间轴的
                    var nowTime = new Date().format("yyyyMMddhhmmss");
                    if ($lastChat.length < 1) {
                        // 生成带有时间轴的
                        $(" <div class='clear-float' data-beforeTime='" + nowTime + "'>\n" +
                            "                        <div class='author-name'>\n" +
                            "                            <small class='chat-date'>" + Totoro.getNowHourAndMinute() + "</small>\n" +
                            "                        </div>\n" +
                            "                        <div class='chat-that-left chat'>\n" +
                            "                            <div class='chat-avatars'>\n" +
                            "                                <img src='"+thatHead+"' alt='头像'>\n" +
                            "                            </div>\n" +
                            "                            <div class='chat-message'>" + text + "</div>\n" +
                            "                        </div>\n" +
                            "                    </div>").appendTo($(".cc-content"));
                        // 将滚动条自动滚动到最下方
                        var mainContainer = $('.cc-content');
                        mainContainer.scrollTop(9999999);
                        return false;
                    }

                    var beforeTime = $lastChat.attr("data-beforetime");
                    var st = getMinuteInDates(beforeTime, nowTime);
                    if (st >= 5) {
                        // 生成带有时间轴的
                        $(" <div class='clear-float' data-beforeTime='" + nowTime + "'>\n" +
                            "                        <div class='author-name'>\n" +
                            "                            <small class='chat-date'>" + Totoro.getNowHourAndMinute() + "</small>\n" +
                            "                        </div>\n" +
                            "                        <div class='chat-that-left chat'>\n" +
                            "                            <div class='chat-avatars'>\n" +
                            "                                <img src='"+thatHead+"' alt='头像'>\n" +
                            "                            </div>\n" +
                            "                            <div class='chat-message'>" + text + "</div>\n" +
                            "                        </div>\n" +
                            "                    </div>").appendTo($(".cc-content"));
                    } else {
                        // 生成没有时间的
                        $("<div class='chat-that-left chat'>\n" +
                            "                            <div class='chat-avatars'>\n" +
                            "                                <img src='"+thatHead+"' alt='头像'>\n" +
                            "                            </div>\n" +
                            "                            <div class='chat-message'>" + text + "</div>\n" +
                            "                        </div>").appendTo($(".cc-content").children(".clear-float:last-child"));
                    }
                    // 将滚动条自动滚动到最下方
                    var mainContainer = $('.cc-content');
                    mainContainer.scrollTop(9999999);
                    return false;
                }

                // 如果打开了，但是没有选中发来信息的那个聊天栏，则给指定的聊天栏加上消息提示
                // 拿到上方发送方发送消息过来的那个左侧选择栏，给他来个次数消息提示
                var $messageCountTip = $sendMainChat.find(".bc-badge");
                // 将这个提示的次数加一
                var count = parseInt($messageCountTip.attr("data-count"))+1;
                $messageCountTip.attr("data-count", count).text(count);
                // 如果被隐藏了，则显示
                if($messageCountTip.css("display")=="none"){
                    $messageCountTip.show();
                }
                return false;
            }

            // 如果没有打开聊天面板，那么调用父级页面左下角的提示
            var $tipPanel = $(".popup-wrap.down-box",window.parent.document);
            $tipPanel.fadeIn(500);
            // 过10秒自动关闭
            setTimeout( v=>{
                if($tipPanel.css("display")!="none"){
                    $tipPanel.fadeOut(500);
                }
            }, 10000);
        }
        function onOpen(event) {
            console.log("握手成功");
        }
        function onError(event) {
            alert(event.data);
        }
    });
    };




$("#text-input").niceScroll({
    cursorcolor: "#ccc", //#CC0071 光标颜色
    cursoropacitymax: 1, //改变不透明度非常光标处于活动状态（scrollabar“可见”状态），范围从1到0
    touchbehavior: false, //使光标拖动滚动像在台式电脑触摸设备
    cursorwidth: "7px", //像素光标的宽度
    cursorborder: "0", //    游标边框css定义
    cursorborderradius: "7px", //以像素为光标边界半径
    autohidemode: true //是否隐藏滚动条
});

$(function () {
    // 点击父页面的消息提示，直接关闭消息
    $(".popup-wrap.down-box",window.parent.document).click(function () {
        $(this).fadeOut(100);
    })

    // 点击选哪个聊天用户
    $(".cl-seller-item").click(function () {
        if ($(this).hasClass("selected")) {
        return false;
         }
        // 将这个聊天用户的消息提示变为0并隐藏
        $(this).find(".bc-badge").attr("data-count", 0).text(0).hide();
        $(this).addClass("selected").siblings().removeClass("selected");
        // 从数据库将详细提示变为0
        var smId = $(this).attr("data-sm-id");
        $.post("/chat/alreadyReadChat.htm", {"suMainChatId": smId});
        // 获取点击的这个用户的用户名和详情简介
        var thatName = $(this).find(".cl-seller-name").text();
        var thatInfo = $(this).attr("data-detail");
        // 获取点击的这个用户的店铺id和名字
        var sid = $(this).attr("data-sid");
        var thatName = $(this).find(".cl-seller-name").text();
        // 获得对方的头像
        var thatHead = $(this).find(".cl-seller-head img").attr("src");
        // 渲染在聊天框上方
        $(".cc-seller-nsm .cc-seller-name.ccs-nsm").find("span").text(thatName);
        $(".cc-seller-nsm .cc-seller-message").find("span").text(thatInfo);
        // 获取选中的这个聊天用户面板id
        var suMainChatId = $(this).attr("data-sm-id");

        // 将数据渲染在右边
        $(".cr-shop-head img").attr("src", thatHead);
        $(".cr-shop-name p").text(thatName);
        $(".cr-enter-shop").html("");
        $("#shopRecommend").html("");
        if(sid != 0){
            $("#moreRe").attr("href", "/shop/search.htm?brandId="+sid+"&orderType=hotsell_desc");
            $(".cr-enter-shop").html(" <a href='/shop/view_shop?brandId="+ sid +"' target='_blank'>\n" +
                "                            <input type='button' value='进入店铺'/>\n" +
                "                        </a>");

            // 获得本店推荐
            $.post("/chat/selfShopRecommend.htm", {"sid":sid}, res=>{
                res = eval("("+ res +")");
                var response = res.data;
                for (let i = 0; i < response.length; i++) {
                    var data = response[i];
                    var productId = data['id'];
                    var productImage = data['productImages'][0]['imagePath'];
                    var productnowPrice = parseFloat(data['nowPrice']);
                    var productBeforePrice = parseFloat(data['beforePrice']);
                    $(" <li>\n" +
                        "                                    <div class='recommend-shop'>\n" +
                        "                                        <div class='recommend-shop-img'>\n" +
                        "                                            <a href='/buy.htm?pid="+ productId +"' target='_blank'>\n" +
                        "                                                <img src='"+ productImage +"'/>\n" +
                        "                                            </a>\n" +
                        "                                        </div>\n" +
                        "                                        <div class='recommend-tips'>\n" +
                        "                                            <s>￥"+ productnowPrice +" </s>\n" +
                        "                                            "+ ((productBeforePrice < productnowPrice) && productBeforePrice!=0?'<span> ￥'+ productBeforePrice +'</span>':'') +"\n" +
                        "                                        </div>\n" +
                        "                                    </div>\n" +
                        "                                </li>").appendTo($("#shopRecommend"));
                }
            });
        }


        // 将当前选中的用户聊天栏里的 所有聊天记录动态渲染在右边聊天框中
        $.post("/chat/getMainChatDownChatContent.htm", {"suMainChatId": suMainChatId}, res=>{
            var response = eval("("+ res +")").data;
            if(response.length < 1){
                return false;
            }
            // 获取所有的键，继续遍历操作
            var chatKeys = new Array();
            for (const responseKey in response) {
                chatKeys.push(responseKey);
            }
            // 先将原来聊天框的内容清空
            $(".cc-content").html("");
            // 动态生成思路：第一层循环先分组生成好指定时间段，第二层循环生成双方的消息记录
            for (let i = 0; i < chatKeys.length; i++) {
                // 获取本次外层循环里的第一条消息记录的时间
                var firstDate = response[chatKeys[i]][0]['createTime'];
                var $parentDateBox = $("<div class='clear-float' data-beforetime='"+Totoro.formatWechatAgainDate(firstDate)+"'>\n" +
                    "                            <div class='author-name'>\n" +
                    "                                <small class='chat-date'>"+Totoro.toWeChatDate(firstDate)+"</small>\n" +
                    "                            </div>\n" +
                    "                        </div>").appendTo($(".cc-content"));
                // 生成消息记录
                var nowTimePartDownChats = response[chatKeys[i]];
                for (let j = 0; j < nowTimePartDownChats.length; j++) {
                    // 获取发送方和接收方的uid，判断本次查看者是发送方还是输入方
                    var fromUid = nowTimePartDownChats[j]['fromUid'];
                    var toUid = nowTimePartDownChats[j]['toUid'];
                    var selfUid = $(".chat-page").attr("data-from-uid");
                    // 获取发送的消息
                    var chatText = nowTimePartDownChats[j]['chatText'];
                    if(fromUid == selfUid){
                        var $thisChat = $("<div class='chat-that-right chat'>\n" +
                            "                                        <div class='chat-message'>"+chatText+"</div>\n" +
                            "                                        <div class='chat-avatars'>\n" +
                            "                                            <img src='/static/img/seller/seller_default_head.png' alt='头像'>\n" +
                            "                                        </div>\n" +
                            "                                    </div>").appendTo($parentDateBox);
                    }
                    if(toUid == selfUid){
                        var $thatChat = $("<div class='chat-that-left chat'>\n" +
                            "                                        <div class='chat-avatars'>\n" +
                            "                                            <img src='"+thatHead+"' alt='头像'>\n" +
                            "                                        </div>\n" +
                            "                                        <div class='chat-message'>\n" +
                            "                                                "+chatText+"\n" +
                            "                                        </div>\n" +
                            "                                    </div>").appendTo($parentDateBox);
                    }
                    // 将滚动条自动滚动到最下方
                    var mainContainer = $('.cc-content');
                    mainContainer.scrollTop(9999999);
                }
            }
        });
    });


    // 点击发送消息
    $("#send").click(function () {
        // 获取div里输入框的值
        var text = $("#text-input").html();
        // 如果没有填写发送内容
        if(text.length<1){
            // 显示隐藏 消息为空提示div
            $(".input-empty").show(10);
            setTimeout(function () {
                $(".input-empty").hide(10);
            },1000);
            return false;
        }


        // 发送消息给指定接收方 发送一个json
        var dataSource = $(".cl-seller-item.selected");
        let jsObject = {
            suMainChatId: dataSource.attr("data-sm-id"),
            sendMessage: text,
            sendType: 0,
            fromUid: dataSource.attr("data-from-uid"),
            toUid: dataSource.attr("data-to-uid")};
        webSocket.send(JSON.stringify(jsObject));
        // 如果发送成功，将消息保存数据库，再生成进入聊天框中，如果对面用户是在线的，则通信给他
        // 判断上一次发送的时间是否与本次时间相差五分钟，如果大于或等于五分钟，则新建一条时间线
        var $lastChat = $(".cc-content").children(".clear-float:last-child");
        var nowTime = new Date().format("yyyyMMddhhmmss");
        // 如果没有消息记录，则默认生成带有时间轴的
        if($lastChat.length < 1){
            // 生成带有时间轴的
            $(" <div class='clear-float' data-beforeTime='"+nowTime+"'>\n" +
                "                        <div class='author-name'>\n" +
                "                            <small class='chat-date'>"+Totoro.getNowHourAndMinute()+"</small>\n" +
                "                        </div>\n" +
                "                        <div class='chat-that-right chat'>\n" +
                "                            <div class='chat-message'>"+text+"</div>\n" +
                "                            <div class='chat-avatars'>\n" +
                "                                <img src='/static/img/seller/seller_default_head.png' alt='头像'>\n" +
                "                            </div>\n" +
                "                        </div>\n" +
                "                    </div>").appendTo($(".cc-content"));
            // 左侧方最新消息
            // 获得选中的左侧用户
            var $selectedMainChatPanel = $(".cl-seller-item.selected");
            $selectedMainChatPanel.find(".cl-seller-synopsis").html(Totoro.cutOutImgPrefix(text, "[图片]"));
            // 将滚动条自动滚动到最下方
            var mainContainer = $('.cc-content');
            mainContainer.scrollTop(9999999);
            $("#text-input").text("");
            return false;
        }

        var beforeTime = $lastChat.attr("data-beforetime");
        var st=getMinuteInDates(beforeTime,nowTime);
        if(st > 5){
            // 生成带有时间轴的
            $(" <div class='clear-float' data-beforeTime='"+nowTime+"'>\n" +
                "                        <div class='author-name'>\n" +
                "                            <small class='chat-date'>"+Totoro.getNowHourAndMinute()+"</small>\n" +
                "                        </div>\n" +
                "                        <div class='chat-that-right chat'>\n" +
                "                            <div class='chat-message'>"+text+"</div>\n" +
                "                            <div class='chat-avatars'>\n" +
                "                                <img src='/static/img/seller/seller_default_head.png' alt='头像'>\n" +
                "                            </div>\n" +
                "                        </div>\n" +
                "                    </div>").appendTo($(".cc-content"));
        } else{
            // 生成没有时间的
            $("<div class='chat-that-right chat'>\n" +
                "                            <div class='chat-message'>"+text+"</div>\n" +
                "                            <div class='chat-avatars'>\n" +
                "                                <img src='/static/img/seller/seller_default_head.png' alt='头像'>\n" +
                "                            </div>\n" +
                "                        </div>").appendTo($(".cc-content").children(".clear-float:last-child"));
        }
        // 将滚动条自动滚动到最下方
        var mainContainer = $('.cc-content');
        // 左侧方最新消息
        // 获得选中的左侧用户
        var $selectedMainChatPanel = $(".cl-seller-item.selected");
        // 将刚刚发送的值渲染上去
        $selectedMainChatPanel.find(".cl-seller-synopsis").html(text);
        mainContainer.scrollTop(9999999);
        $("#text-input").text("");
    });

    // 如果点击其他地方，消息空提示立刻关闭
    $(document).click(function () {
        if($(".input-empty").css("display") == "block"){
            if($(event.target).attr("id") == "send"){
                return false;
            }
            $(".input-empty").hide(10);
        }
    })

    // 点击关闭窗口
    $("#close").click(function () {
        // 控制父元素
        $("#adc",window.parent.document).hide(500);
    });

    // 父页面直接使用阿里巴巴打开该聊天框，判断登录
    $(".ww-online",window.parent.document).click(function () {
        var toUid = $(this).attr("data-to-uid");
        $.ajaxSettings.async = false;
        $.post("/user_logic/userStatus.htm", res=>{
           if(res == "no"){
               var $btn = $("#notLogin",window.parent.document);
               $btn.click();
           } else{
               // 执行打开聊天框之前的业务处理
               $.post("/chat/beforeAliOpenChatDialog.htm", {"toUid": toUid});
               var $chatIframe = $(".chat-iframe", window.parent.document);
               $chatIframe.attr("src", "/chat/openChatDialog.htm");
               var $pb = $(".chat-box",window.parent.document);
               var isVb = $pb.css("display");
               // 点击打开聊天框，让表情div跟随聊天页面
               var top = $pb.css("top");
               var left = $pb.css("left");
               $("#emoji_container_1").css({"top":(parseInt(top)+110),"left":(parseInt(left)-150)});
               if(isVb.toString() == "block"){
                   $("#repeat-error",window.parent.document).click();
                   return false;
               }
               $pb.show(500);
               // 将滚动条自动滚动到最下方
               var mainContainer = $('.cc-content');
               mainContainer.scrollTop(99999999);
               // 刷新子页面，以便获取最新数据，延迟半秒是因为打开子页面有半秒动画时间
               setTimeout(function () {
                   $pb.css("overflow", "");
                   window.parent.frames["adc"].location.reload();
               },500);
           }
        });
    });

    // 不使用阿里旺旺打开聊天面板，而是直接打开
    $(".chat-suspension",window.parent.document).click(function () {
        $.post("/user_logic/userStatus.htm", res=> {
            if (res == "no") {
                var $btn = $("#notLogin", window.parent.document);
                $btn.click();
            } else {
                var $pb = $(window.parent.document.getElementById("adc"));
                var isVb = $pb.css("display");
                // 点击打开聊天框，让表情div跟随聊天页面
                var top = $pb.css("top");
                var left = $pb.css("left");
                $("#emoji_container_1").css({"top":(parseInt(top)-200)+"px","left":(parseInt(left))+"px"});
                if(isVb.toString() == "block"){
                    $(window.parent.document.getElementById("repeat-error")).click();
                    return false;
                }
                // 火狐狸浏览器不能使用动画
                var nowBrowser = Totoro.getWeb();
                if(nowBrowser == 'Firefox'){
                    $pb.show();
                } else{
                    $pb.slideDown(500);
                }
                // 将滚动条自动滚动到最下方
                var mainContainer = $('.cc-content');
                mainContainer.scrollTop(9999999);
                // 刷新子页面，以便获取最新数据，延迟半秒是因为打开子页面有半秒动画时间
                setTimeout(function () {
                    $pb.css("overflow", "");
                    window.parent.frames["adc"].location.reload();
                },500);
            }
        });
    })
})

